<template>
  <view class="content">
    <view class="body">
      <img src="@/static/icon.png" class="icon" :use-anchor="true" />
      <!-- 标题和播音按钮 -->
      <view class="title">
        <uni-row>
          <uni-col :span="24"
            ><view>{{ view.bookName }}</view>
          </uni-col>
         </uni-row
        ></view
      >
      <!-- 内容区 -->
      <view style="min-height: calc(100% - 200rpx);text-align: justify;">
        <mp-html
          ref="title"
          :tag-style="{ p: 'line-height:50rpx' }"
          :content="view.codeContent"
          @imgtap="stop"
          @play="stop"
        ></mp-html>
      </view>
	  <view v-if="view.codePhone">联系方式：<text style="color:#0066d4" @click = "tophone(view.codePhone)">{{view.codePhone}}</text>  </view>
	   <view style="margin-top:10rpx" v-if="view.codeEmail">邮 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱： {{view.codeEmail}} </view>
	   <!-- 文档展示 -->
	   <view v-if="codeFiles">
		   <view v-for="(item ,index) in view.codeFiles" :key="index" @click="showFile(item)" style="color:#268bda;text-decoration: underline;margin-bottom: 10rpx;">
			   {{item.name}}
		   </view>
	   </view>
    </view>
    <!-- 底下播放器 -->
    <view class="bottom">
      <uni-row>
        <uni-col :span="4">
          <!--  :style="{
              background: 'url(' + http + view.banner + ')',
              'background-size': 'cover',
            }" -->
          <view
            v-if="view.banner"
            class="bookPic"
            :style="{
              background: 'url(' + http + view.banner + ')',
              'background-size': 'cover',
            }"
          >
            <img
              :src="
                require('@/static/' + (isPlay ? 'parse' : 'start') + '.png')
              "
              @click="toPlay"
              style="width: 80rpx; height: 80rpx; margin: 14rpx 0 0 14rpx"
            />
          </view>
        </uni-col>
        <uni-col :span="16">
          <view style="padding: 20rpx 6rpx 20rpx 30rpx">
            <view
              style="
                font-size: 18px;

                font-weight: bold;
                font-family: 宋体;
              "
              >{{ view.bookName }}</view
            >
            <view style="font-size: 14px; margin: 4rpx 0; color: #555">{{
              view.bookAuthor
            }}</view>
          </view>
        </uni-col>
        <uni-col :span="4">
          <view
            style="
              background: #c1b18c;
              text-align: center;
              padding: 10rpx;
              font-size: 15px;
              margin-top: 20rpx;
            "
            >{{ view.bookTypeName }}</view
          >
        </uni-col>
      </uni-row>
    </view>
   <view class="status_bar">
              <!-- 这里是状态栏 -->
          </view>
  </view>
</template>

<script>
import { selectUniqueCodeById ,getAccessToken,readTime} from "@/untils/api";
import http from "@/untils/http";
import VueLazyload from 'vue-lazyload';
import Vue from 'vue';
Vue.use(VueLazyload, {
  // 设置懒加载时的占位图
  loading: 'path/to/loading-image.gif',
  // 设置图片加载失败时的占位图
  error: 'path/to/error-image.png'
});
export default {
  data() {
    return {
      text: "", //通过getText的api获取到的文本内容
      isParse: false, //暂停状态
      isPlay: false, //播放状态
      node: undefined, //富文本所有的节点
      index: undefined, //从插件传过来的索引
      bookId:undefined,//"fc5083ea-e9e7-4cca-94fa-931f5bc75dd7",//书的id
      token:undefined,//百度语音token
      innerAudioContext: uni.createInnerAudioContext(),
      http: http.globalConfig.baseUrl, //把后端指向的地址放在这，调书籍背景图要用
      view: {},
      startTime: undefined,
      endTime: undefined,
	  codeFiles:undefined
    };
  },

  mounted() {

    selectUniqueCodeById({ id: this.bookId,num:Math.random()})
      .then((res) => {
		  if(res.code==200){
		  //判断外部链接
		  if(res.data.codeType==2){
			    window.location.href =res.data.codeLink
		  }else{
			   this.view = res.data;
			   readTime({bookId: this.view.bookId,codeId: this.view.id,})
			  this.codeFiles=res.data.codeFiles.length>0
		  }
       }
		console.log(res,'resssss')
        //把节点放在node里
        this.$nextTick(() => {
          this.node = this.$refs.title.nodes;
          this.text = this.$refs.title.getText();
        });
      })
      .catch((error) => {
        console.log(error);
      });
    //点击单个段落后，从node组件发过来的索引数据，在此处执行以下朗读
    let Arr = [];
    this.$bus.$on("audio", (e, arr) => {
     
      Arr = arr;
      this.isPlay = true;
      this.index = e;
      //this.play(this.node[e].children[0].text);
      this.play(arr[e]);
    });
    //监听暂停
    this.innerAudioContext.onPause(() => {
      this.isParse = true;
    });
    //播放结束后，再顺着后面的内容播放
    this.innerAudioContext.onEnded(() => {
      //播放结束后，把索引i给node再传一次，为了让背景色取消
      this.$bus.$emit("index", this.index);
      if (this.index < Arr.length - 1) {
        this.index++;
        //停止播放后，就继续读Arr后面的内容，先判断一下有内容么
        if (Arr[this.index]) {
          this.$bus.$emit("color", this.index);
          this.play(Arr[this.index]);
        } else {
          this.play(",");
        }
      } else {
        this.index = 0; //读完后把i置为0，不然就再次进else里
        this.isPlay = false; //把读的状态置为false，播放状态图片，
        this.isParse = false; //每次读完一个，都会执行暂停钩子，在整体全读完，给它置为false
      }
    });
  },
  onLoad(param){
	
	 this.bookId=param.id
	//this.bookId="624834e0-b1c3-4c16-b47d-09932c0b1952"

  //console.log( this.bookId,' this.bookId')
  },
  onShow: function () {
    this.getToken()
    this.startTime = new Date();
  },
  beforeDestroy:function(){
	    readTime({bookId: this.view.bookId,codeId: this.view.id,})
		 this.parseMedia(); 
  },

  methods: {
	  //点电话号码打电话
	   tophone(num) {
	  		uni.makePhoneCall({
	  			phoneNumber: num
	  		})
	  	},
		//文档预览
		showFile(file){
			//window.open(this.http+ file.url)
			//window.open('http://www.pfile.com.cn/api/profile/onlinePreview?url='+encodeURIComponent(this.http+ file.url))	
		},
   
    //暂停播放富文本里的视频
    parseMedia() {
      this.$refs.title.pauseMedia();
    },
    stop() {
      this.innerAudioContext.pause();
      this.isPlay = false;
    },
    //点击播放按钮
    toPlay() {
      this.parseMedia();
      this.isPlay ? (this.isPlay = false) : (this.isPlay = true);
      if (this.isPlay) {
        this.playAll();
      } else {
        this.stop();
      }
    },
    //获取百度token值
    getToken() {
      getAccessToken()
        .then((res) => {
          this.token = res.msg;
		  console.log(this.token,'this.token')
        })
        .catch((error) => {
          console.log(error);
        });
    },
    play(content) {
      this.$refs.title.pauseMedia();
      this.innerAudioContext.autoplay = true;
      this.innerAudioContext.play();
      this.innerAudioContext.src =
        "https://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcd&tok=" +
        this.token +
        "&tex=" +
        encodeURIComponent(content) +
        "&spd=5&per=1";
    },
    playAll() {
      //有isParse这个状态，说明是暂停，让它继续播放
      if (this.isParse) {
        this.innerAudioContext.play();
      } else {
        //没有暂停这个状态，就让它从第一个开始读
        this.index = 0;
        /*      if (
          this.node[this.index].children &&
          this.node[this.index].children[0].text
        ) {
          this.$bus.$emit("index", 0);
          this.play(this.node[0].children[0].text);
        } else {
          this.play(",");
        } */
      }
    },
  },
  onHide() {
    this.parseMedia(); // 页面跳转或隐藏时暂停播放
  },
};
</script>

<style>
	page{
	position: relative;
	top:6rpx
	}
.content {
}
.body {
  width: calc(100% - 120rpx);
  margin: 40rpx 40rpx 1rpx 40rpx;
  padding: 0 10rpx;
  padding-bottom: 80rpx;
  overflow: scroll;
  height: calc(100vh - 292rpx);
  background: #f9f8f7;
  border-left: 20rpx solid #cfbbaa;
  border-radius: 20rpx 20rpx 0 0;
  position: relative;
}
.status_bar {
        height: var(--status-bar-height);
        width: 100%;
        background: red;
    }
.icon {
  width: 16px;
  height: 16px;
  position: absolute;
  right: 20rpx;
}
.voice {
  width: 48rpx;
  height: 48rpx;
}
.title {
  width: 100%;
  line-height: 56rpx;
  font-size: 24px;
  padding: 60rpx 0 40rpx 0;
  font-family: "宋体";
  font-weight: bold;
  color: #745443;
  border-bottom: 2rpx dotted #dbd7d0;
}
.bottom {
  width: calc(100% - 80rpx);
  position: relative;
  margin: 0 40rpx;
  background: #dbd1b8;
  border-radius: 0 0 20rpx 20rpx;
}
.bookPic {
  width: 100rpx;
  height: 100rpx;
  margin: 14rpx 0rpx 0 14rpx;
  border-radius: 10rpx;
  /* background: url("http://127.0.0.1:5500/di.jpg"); */
}
</style>
